package com.shundr.common;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.hardware.Camera.Area;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.shundr.R;
import com.shundr.base.BaseActivity;
import com.shundr.common.dao.AreaDao;
import com.shundr.common.model.AreaInfo;
import com.shundr.common.util.JsonUtil;
import com.shundr.common.util.ToastHelper;
import com.shundr.common.view.AutoWrapLineLayout;
import com.shundr.frame.util.LLogger;
import com.shundr.frame.util.StringUtil;

/**
 * choice single area activity in grid mode. 
 * @author zhaoyy
 *
 */
public class ChoiceAreaGridActivity extends BaseActivity {
	
	private AutoWrapLineLayout ll_multi;
	
	private GridView gridView;
	
	private int choiceStep = 0;
	
	private List<AreaInfo> areas;
	private AreaDao dao;
	
	private String selectAreaCode;
	private boolean isCountry;	// 是否需要全国
	private boolean includeAll;	// 是否需要全部省或者市
	
	private int maxSelected = 1;//允许最多选择地址数
	
	private SimpleAdapter adapter;
	
	private Drawable closeDrawable;
	private AreaInfo backItem;
	
	private List<AreaInfo> selectedList = new ArrayList<AreaInfo>();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_choice_area_grid);
		
		isCountry = getIntent().getBooleanExtra("country", true);
		includeAll = getIntent().getBooleanExtra("includeAll", true);
		maxSelected = getIntent().getIntExtra("max", 1);
		
		maxSelected = maxSelected < 1 ? 1 : maxSelected; // 至少要选择一个
		
		String title = getIntent().getStringExtra("title");
		if(!StringUtil.isNull(title)){
			setTitle(title);
		}
		
		ll_multi = (AutoWrapLineLayout) findViewById(R.id.ll_multi);
		
		adapter = new SimpleAdapter();
		gridView = (GridView) findViewById(R.id.gridview);
		gridView.setAdapter(adapter);
		
		gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				
				if (choiceStep > 0 && position == 0) {
					// 选择了返回
					choiceStep--;
					selectAreaCode = selectAreaCode.substring(0, 2);
					initAreaDataWithStep(choiceStep);
				} else {
					AreaInfo info = (AreaInfo) adapter.getItem(position);
					selectAreaCode = info.getCode();
					
					if (checkSelected(info)) {
						addSelectResult(info);
					} else {
						choiceStep++;
						initAreaDataWithStep(choiceStep);
					}
				}
			}
		});
		
		dao = new AreaDao();
		
		initAreaDataWithStep(choiceStep);
		
		// get close drawable
		closeDrawable = getResources().getDrawable(R.drawable.ic_close);
		
		int width = (int) (16 * getResources().getDisplayMetrics().density + 0.5f);
		
		closeDrawable.setBounds(0,  0, width, width);
	}
	
	private boolean checkSelected(AreaInfo selectArea) {
		// 选择了全类型的
		if (selectArea.getCode().equals(selectArea.getParentCode()) 
				|| (StringUtil.isNull(selectAreaCode) && selectArea.getParentCode().equals("00"))) {
			return true;
		}
		// 选择了最小的粒度
		if (choiceStep == 2) {
			return true;
		}
		
		return false;
	}
	
	private void addSelectResult(AreaInfo selectArea) {
		
		if (selectedList.size() >= maxSelected) {
			ToastHelper.toastShort(mContext, String.format("最多只能选择%s个地址。", maxSelected));
			return;
		}
		
		for (AreaInfo a : selectedList) {
			if (a.getCode().equals(selectArea.getCode())) {
				ToastHelper.toastShort(mContext, selectArea.getName() + "已经被选择！");
				return;
			}
		}
		selectedList.add(selectArea);
		ll_multi.addView(getNewTagView(selectArea));
	}
	
	private TextView getNewTagView(AreaInfo info) {
		
		TextView tv = new TextView(mContext);
		
		tv.setTextSize(14);
		tv.setTextColor(getResources().getColor(R.color.white));
		tv.setBackgroundResource(R.drawable.area_tag_bg);
		tv.setGravity(Gravity.CENTER_VERTICAL);
		tv.setCompoundDrawables(null, null, closeDrawable, null);
		tv.setCompoundDrawablePadding(8);
		tv.setText(info.getName());
		tv.setTag(info.getCode());
		tv.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				String name = (String) v.getTag();
				
				removeAreaData(name);
				
				ll_multi.removeView(v);
			}
		});
		return tv;
		
	}
	
	private void removeAreaData(String name) {
		for (AreaInfo a : selectedList) {
			if (a.getCode().equals(name)) {
				selectedList.remove(a);
				break;
			}
		}
	}
	
	private void initAreaDataWithStep(int step) {
		switch (step) {
		case 0:
			
			if (includeAll) {
				areas = dao.getAreasByParent("00");
			} else {
				areas = dao.getAreasByParentWithoutAll("00");
			}
			
			if (!isCountry && areas.size() > 0) {
				areas.remove(0);
			}
			
			break;
		case 1:
			if (includeAll) {
				areas = dao.getAreasByParent(selectAreaCode);
			} else {
				areas = dao.getAreasByParentWithoutAll(selectAreaCode);
			}
			areas.add(0, getBackItem());
			break;
		case 2:
			if (includeAll) {
				areas = dao.getAreasByParent(selectAreaCode);
			} else {
				areas = dao.getAreasByParentWithoutAll(selectAreaCode);
			}
			areas.add(0, getBackItem());
			break;
		default:
			break;
		}
		
		if (areas.size() > 1) {
			adapter.setData(areas);
		}
	}
	
	private AreaInfo getBackItem() {
		if (backItem == null) {
			backItem = new AreaInfo();
			backItem.setName("返回");
		}
		
		return backItem;
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		
		getSupportMenuInflater().inflate(R.menu.menu_confirm, menu);
		
		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		
		switch (item.getItemId()) {
		case R.id.menu_confirm:
			
			if (selectedList.size() <= 0) {
				ToastHelper.toastShort(mContext, "请先选择一个地址");
			} else {
				Intent intent = new Intent();
				String json = JsonUtil.toJson(selectedList).toString();
				LLogger.e(json);
				intent.putExtra("json", json);
				setResult(502,intent);
				finish();
			}
			
			break;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	
	class SimpleAdapter extends BaseAdapter {
		LayoutInflater inflater;
		ViewHold viewhold = null;
		List<AreaInfo> mList = new ArrayList<AreaInfo>();

		public SimpleAdapter() {
			super();
			inflater = LayoutInflater.from(mContext);
		}
		
		public void setData(List<AreaInfo> list) {
			mList = list;
			
			notifyDataSetChanged();
		}

		@Override
		public int getCount() {
			return mList.size();
		}

		@Override
		public Object getItem(int position) {
			return mList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@SuppressLint("InflateParams")
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			viewhold = null;
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.view_screeing_gridview_item, null);
				viewhold = new ViewHold();
				viewhold.itemText = (TextView) convertView.findViewById(R.id.text);
				convertView.setTag(viewhold);
			} else {
				viewhold = (ViewHold) convertView.getTag();
			}
			try {
				viewhold.itemText.setText(mList.get(position).getName());
				
				if (position == 0) {
					// back item
					viewhold.itemText.setTextColor(getResources().getColor(
							choiceStep > 0 ? R.color.btn_green_light_dark : R.color.gray));
				} else {
					viewhold.itemText.setTextColor(getResources().getColor(R.color.gray));
				}
				
			} catch (Exception e) {
				e.printStackTrace();
			}
			return convertView;
		}

		class ViewHold {
			TextView itemText;
		}
	}

}
